package com.library.controller;


import com.library.bean.User;
import com.library.service.BookService;
import com.library.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private BookService bookService;

    @RequestMapping("/register")
    public String register(MultipartFile avatar,@Valid User user, BindingResult bindingResult, Model model) {
        System.out.println(user);
        if (bindingResult.hasErrors()) {
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            Map<String, String> errors = new HashMap<>();
            for (FieldError fieldError : fieldErrors) {
                errors.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            model.addAttribute("errors", errors);
            return "forward:register.jsp";
        }
        int insertUser = userService.insertUser(user);

        if (insertUser == -1) {
            model.addAttribute("msg", "用户名已存在");
            return "forward:register.jsp";
        }

        if(avatar != null && !avatar.isEmpty() && avatar.getContentType().contains("image")){
            try {
                String fileName = avatar.getOriginalFilename();//获取文件原始文件名
                String newName = System.currentTimeMillis()+fileName;
                String savePath = "d:/headImgs/"+newName;//确定 文件存储的路径
                String visitPath = "/Library-Web/headImgs/"+newName;
                avatar.transferTo(new File(savePath));
                userService.updateHeadImg(user.getUserName(),visitPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        model.addAttribute("userMess", user);
        return "forward:success.jsp";
    }


    @RequestMapping("/login")
    public String login(User user, Model model, HttpSession session) {
        Map<String, Object> map = userService.selectUser(user);
        if(map.containsKey("loginUser")){
            session.setAttribute("loginUser",map.get("loginUser"));
            return "redirect:/books.jsp";
        }
        model.addAttribute("msg",map.get("msg"));


        return "forward:/login.jsp";
    }
}
